package org.qee.mq.custom;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

import java.io.IOException;
import java.text.SimpleDateFormat;

/**
 * @ProjectName: learning
 * @Package: org.qee.mq.custom
 * @ClassName: JsonValueSerialization
 * @Description:
 * @Date: 2021/12/20 11:09 上午
 * @Version: 1.0
 */
public class JsonValueSerialization implements ValueSerialization {

    private static ObjectMapper objectMapper = new ObjectMapper();

    // 日起格式化
    private static final String STANDARD_FORMAT = "yyyy-MM-dd hh:mm:ss";

    static {
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.setDateFormat(new SimpleDateFormat(STANDARD_FORMAT));
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    @Override
    public byte[] serialize(Object value) throws IOException {
        return value instanceof String ? ((String) value).getBytes() : objectMapper.writeValueAsBytes(value);
    }

    @Override
    public <T> T deserialize(byte[] bytes, Class<T> clzz) throws IOException {
        return objectMapper.readValue(bytes, clzz);
    }

}
